<!doctype html>



  


<html class="theme-next muse use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="spring,ioc," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="简介
层级示意图&amp;amp;接口功能介绍
原理分析
小结">
<meta property="og:type" content="article">
<meta property="og:title" content="源码角度解析SpringIoC的机制">
<meta property="og:url" content="http://yoursite.com/2016/08/28/spring-ioc-1/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="简介
层级示意图&amp;amp;接口功能介绍
原理分析
小结">
<meta property="og:image" content="http://www.blogjava.net/images/blogjava_net/zhanglongsr/container_inner.jpg">
<meta property="og:image" content="http://www.blogjava.net/images/blogjava_net/zhanglongsr/container_outer.jpg">
<meta property="og:updated_time" content="2017-01-19T07:14:13.864Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="源码角度解析SpringIoC的机制">
<meta name="twitter:description" content="简介
层级示意图&amp;amp;接口功能介绍
原理分析
小结">
<meta name="twitter:image" content="http://www.blogjava.net/images/blogjava_net/zhanglongsr/container_inner.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/08/28/spring-ioc-1/"/>

  <title> 源码角度解析SpringIoC的机制 | 个人博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">个人博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">随便写点什么</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                源码角度解析SpringIoC的机制
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T15:38:25+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/spring/" itemprop="url" rel="index">
                    <span itemprop="name">spring</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/08/28/spring-ioc-1/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/08/28/spring-ioc-1/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<blockquote>
<ul>
<li>简介</li>
<li>层级示意图&amp;接口功能介绍</li>
<li>原理分析</li>
<li>小结</li>
</ul>
</blockquote>
<hr>
<a id="more"></a>
<h3 id="1-简介"><a href="#1-简介" class="headerlink" title="1. 简介"></a>1. 简介</h3><pre><code>IoC作为Spring的核心功能之一，内部继承体系错综复杂，下面我们来对它剥丝抽茧的分析一波。
首先，从整体上看Spring容器可以分为两大部分：外部容器和内部容器。外部容器指的是ApplicationContext接口的实现类，我们写程序时也可能经常会用到它。内部容器是BeanFactory的实现类，内部调用较多。
</code></pre><h3 id="2-层级示意图"><a href="#2-层级示意图" class="headerlink" title="2. 层级示意图"></a>2. 层级示意图</h3><p>#####1.内部容器层级示意图<br><img src="http://www.blogjava.net/images/blogjava_net/zhanglongsr/container_inner.jpg" alt="pub-sub"></p>
<p>位于顶层的HierarchicalBeanFactory，AutowireCapableBeanFactory，ListableBeanFactory接口均继承于BeanFactory。</p>
<p>ok，那大致介绍下这些接口完成或者扩展了什么功能。</p>
<p>1.BeanFactory:定义了最基础的获取bean的方法，以及一些bean的匹配操作（单例模式，类型匹配等）。</p>
<p>2.HierarchicalBeanFactory:扩展了BeanFactory，提供了获取双亲BeanFactory的方法。其实就是让你可以有一个父BeanFactory</p>
<p>3.ListableBeanFactory：同样扩展了BeanFactory，它可以列举出所有bean的实例而非通过客户端给出的bean name一个一个搜索。感觉预加载的时候比较有用。</p>
<p>4.AutowireCapableBeanFactory：从接口定义的方法中可以看出，该接口主要用于自动装配bean，包括创建bean、装配bean的属性、装配bean的依赖、注册bean等一整套流程。该接口对于外部的应用程序而言，几乎不需要使用，其只应用于Spring容器的内部管理，实际上只有内部BeanFactory实现此功能。</p>
<p>5.ConfigurableBeanFactory：提供bean的属性配置功能，需要对bean进行配置的BeanFactory都会实现它。</p>
<p>6.ConfigurableListableBeanFactory：相比于上面，它可以修改bean definition，以及它可以提前实例化以单例模式存在的bean。</p>
<p>7.AbstractBeanFactory：BeanFactory的一个抽象基类，提供了对bean的基本操作。</p>
<p>8.AbstractAutowireCapableBeanFactory：与上面最主要的区别就是实现了默认的bean创建方法createBean()。</p>
<p>9.DefaultListableBeanFactory：第一个可以真正直接拿来用的容器。官方释义，在访问bean前，先注册所有的definition（可能从bean definition配置文件中）。使用预先建立的bean定义元数据对象，从本地的bean definition表（其实就是一个map）中查询bean definition因而将不会花费太多成本。</p>
<p>10.SingletonBeanRegistry：提供单例注册,查询服务。</p>
<p>11.DefaultSingletonBeanRegistry：实现单例与DisposableBean的生命周期管理(创建,维护,销毁)</p>
<p>12.FactoryBeanRegistrySupport：添加工厂方式创建类FactoryBean的支持。</p>
<p>#####2.外部容器层级示意图<br><img src="http://www.blogjava.net/images/blogjava_net/zhanglongsr/container_outer.jpg" alt="out-container"><br>相比于直接扩展自BeanFactory的简单容器，那么实现自ApplicationContext的容器可以称之为高级容器。同时，在以下方面的功能有所加强。</p>
<blockquote>
<p>1.支持应用事件，该功能源于ApplicationEventPublisher接口。引入事件机制后，便于bean的管理。<br>2.资源访问，该特性源于Resource，ResourceLoader。以此，我们可以从不同的地方来获取bean信息。<br>3.支持不同的信息源，该接口这里没有标出，是源自MessageSource，可以支持国际化，为多语言版本的应用提供支持。</p>
</blockquote>
<p>那还是大致介绍一下这些接口以及抽象类的基本功能。</p>
<p>   1.ApplicationContext： 首先是一个外部容器的中心接口，提供应用程序的配置。根据官方释意：一个ApplicationContext提供如下功能：</p>
<blockquote>
<p>·用来访问应用程序组件的bean factory方法，其继承自ListableBeanFactory。<br>    ·能以通用的方式加载文件资源，其继承自ResourceLoader。<br>        ·能够向注册的监听器发布事件，其继承自ApplicationEventPublisher。<br>        ·能够解析消息，支持国际化，继承自MessageSource。<br>        ·继承自父上下文，后代上下文中的Definition将总能获得优先级，这意味着，例如，一个单亲上下文能够被整个应用程序使用，而每个servlet有它自己的孩子上下文，它独立于其他的servlet。</p>
</blockquote>
<p>2.ConfigurableApplicationContext：配置和生命周期方法被封装在这里。</p>
<p>3.AbstractApplicationContext：ApplicationContext的基本抽象实现，提供了BeanFactory的后置processor的注册、应用上下文的双亲维护、资源加载的功能。</p>
<p>4.AbstractRefreshableApplicationContext：官方释义，ApplicationContext的基类的实现，其支持多次refreshs，每次创建一个内部bean工厂实例。通常（但不一定），一个上下文将会由一系列的配置定位来驱动，加载bean definations。</p>
<p>5.AbstractRefreshableConfigApplicationContext：主要为配置文件位置的设置提供入口，即实现了setConfigLocation方法。这就提供了不依赖于Spring的且更灵活、通用的配置注入方式。</p>
<p>6.AbstractXmlApplicationContext：ApplicationContext的便利基类的实现。用于提取包含bean definition信息的XML文档，该文档由XmlBeanDefinitionReader负责解释。</p>
<p>7.FileSystemXmlApplicationContext：这是一个简单的，一站式的便利的ApplicationContext的基本实现。</p>
<p>8.ResourceLoader：加载资源(类路径和文件路径)的策略接口，ApplicationContext需要提供此功能来加载资源。</p>
<p>9.ResourcePatternResolver：解释位置模式的策略接口，其扩展自ResourcePatternResolver接口。</p>
<p>###3.原理分析</p>
<p>#####1.内部容器的启动及加载过程<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/*</span></div><div class="line">* 可以看到XmlBeanFactroy的代码还是比较简单的，只是初始化了一个用于读取XML形式的BeanDefinition的对象，除此之外并没有太多的操作。</div><div class="line">* 因为主要的BeanFactory的基本实现都已经在DefaultListableBeanFactory中完成了。</div><div class="line">*/</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XmlBeanFactory</span> <span class="keyword">extends</span> <span class="title">DefaultListableBeanFactory</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="keyword">private</span> <span class="keyword">final</span> XmlBeanDefinitionReader reader = <span class="keyword">new</span> XmlBeanDefinitionReader(<span class="keyword">this</span>);</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">XmlBeanFactory</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeansException </span>&#123;</div><div class="line">		<span class="keyword">this</span>(resource, <span class="keyword">null</span>);</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">XmlBeanFactory</span><span class="params">(Resource resource, BeanFactory parentBeanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</div><div class="line">		<span class="keyword">super</span>(parentBeanFactory);</div><div class="line">		<span class="keyword">this</span>.reader.loadBeanDefinitions(resource);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>以上可以看出XmlBeanFactory本身并没有做什么，真正扩展的是XmlBeanDefinitionReader，因为它需要去读取XML形式的BeanDefinition，而BeanFactory的基本功能都在DefaultListableBeanFactory中实现了，XmlBeanFactory直接继承过来。<br>在初始化父容器的过程中，没有什么特别的。<br>来看下XmlBeanDefinitionReader如何读取BeanDefinition。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//这个的资源形式是要以Resource形式给出的，比如：</span></div><div class="line"><span class="comment">//ClassPathResource res = new ClassPathResource("bean.xml");</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</div><div class="line">		<span class="keyword">return</span> loadBeanDefinitions(<span class="keyword">new</span> EncodedResource(resource));</div><div class="line">	&#125;</div><div class="line">	</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(EncodedResource encodedResource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</div><div class="line">		Assert.notNull(encodedResource, <span class="string">"EncodedResource must not be null"</span>);</div><div class="line">		<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</div><div class="line">			logger.info(<span class="string">"Loading XML bean definitions from "</span> + encodedResource.getResource());</div><div class="line">		&#125;</div><div class="line"><span class="comment">//这里开始没搞明白，为什么用一个ThreadLocal，不过currentResources这个Set应该是用来判断资源是否循环加载的。</span></div><div class="line">		Set&lt;EncodedResource&gt; currentResources = <span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.get();</div><div class="line">		<span class="keyword">if</span> (currentResources == <span class="keyword">null</span>) &#123;</div><div class="line">			currentResources = <span class="keyword">new</span> HashSet&lt;EncodedResource&gt;(<span class="number">4</span>);</div><div class="line">			<span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.set(currentResources);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">if</span> (!currentResources.add(encodedResource)) &#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</div><div class="line">					<span class="string">"Detected cyclic loading of "</span> + encodedResource + <span class="string">" - check your import definitions!"</span>);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">		<span class="comment">//获取目标资源经spring包装后的IO流</span></div><div class="line">			InputStream inputStream = encodedResource.getResource().getInputStream();</div><div class="line">			<span class="keyword">try</span> &#123;</div><div class="line">				InputSource inputSource = <span class="keyword">new</span> InputSource(inputStream);</div><div class="line">				<span class="keyword">if</span> (encodedResource.getEncoding() != <span class="keyword">null</span>) &#123;</div><div class="line">					inputSource.setEncoding(encodedResource.getEncoding());</div><div class="line">				&#125;</div><div class="line">				<span class="comment">//进行bean加载的入口</span></div><div class="line">				<span class="keyword">return</span> doLoadBeanDefinitions(inputSource, encodedResource.getResource());</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">finally</span> &#123;</div><div class="line">				inputStream.close();</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">catch</span> (IOException ex) &#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</div><div class="line">					<span class="string">"IOException parsing XML document from "</span> + encodedResource.getResource(), ex);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">finally</span> &#123;</div><div class="line">		<span class="comment">//这里remove掉了之前刚加载好的资源应用，因为resourcesCurrentlyBeingLoaded这个东西的意义应该是当前正在被加载的资源，所以，资源加载完后，会从Set中remove掉。</span></div><div class="line">			currentResources.remove(encodedResource);</div><div class="line">			<span class="keyword">if</span> (currentResources.isEmpty()) &#123;</div><div class="line">				<span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.remove();</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>在分析doLoadBeanDefinitions()之前，还有其他部分细节在这里说下。比如<strong>Set<encodedresource> currentResources = this.resourcesCurrentlyBeingLoaded.get()</encodedresource></strong>，为何要用ThreadLocal来存这个Set，根据final代码块的执行过程，推测出该Set应该是保存了即将要被加载或者正在被加载的资源。而loadBeanDefinitions()也没用进行额外的多线程安全的控制，所以借助于ThreadLocal，使得如果存在多线程共同加载，那么，各个线程加载各自的资源，避免出现预期被加载的资源在多线程环境下被其他线程覆盖的情况。<br>那继续说<strong>doLoadBeanDefinitions()</strong>。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">doLoadBeanDefinitions</span><span class="params">(InputSource inputSource, Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">		<span class="comment">//使用标准的JAXP配置的xml解析器从Resource中加载到Document。这里就不展开说明XML内容加载到Document的过程了。</span></div><div class="line">			Document doc = doLoadDocument(inputSource, resource);</div><div class="line">			<span class="comment">//根据加载的Document注册Bean definition。</span></div><div class="line">			<span class="keyword">return</span> registerBeanDefinitions(doc, resource);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">catch</span></div><div class="line">		...</div><div class="line">		</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</div><div class="line">	<span class="comment">//根据Document的实际类型创建对应的Reader，将Document中的内容读取到BeanDefinition中。</span></div><div class="line">		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();</div><div class="line">		<span class="comment">//获取已注册的bean definition数量</span></div><div class="line">		<span class="keyword">int</span> countBefore = getRegistry().getBeanDefinitionCount();</div><div class="line">		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));</div><div class="line">		<span class="comment">//返回从resource中成功注册的bean definition数量</span></div><div class="line">		<span class="keyword">return</span> getRegistry().getBeanDefinitionCount() - countBefore;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>关于BeanDefinition的载入要分为两步，一是讲XML的内容解析到Document，二是讲Document中的内容按照Spring的规定解析成bean。第一步是在DefaultDocumentLoader中完成的，第二步在BeanDefinitionDocumentReader中完成。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, XmlReaderContext readerContext)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.readerContext = readerContext;</div><div class="line">		logger.debug(<span class="string">"Loading bean definitions"</span>);</div><div class="line">		Element root = doc.getDocumentElement();</div><div class="line">		doRegisterBeanDefinitions(root);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="comment">//从root结点开始解析，将每一个bean都进行注册</span></div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doRegisterBeanDefinitions</span><span class="params">(Element root)</span> </span>&#123;</div><div class="line">	<span class="comment">//实际上真正的解析过程是在BeanDefinitionParserDelegate这个代理中（processBeanDefinition）进行的。</span></div><div class="line">		BeanDefinitionParserDelegate parent = <span class="keyword">this</span>.delegate;</div><div class="line">		<span class="keyword">this</span>.delegate = createDelegate(getReaderContext(), root, parent);</div><div class="line"><span class="comment">//判断XML中的命名空间是否是默认值（http://www.springframework.org/schema/beans）</span></div><div class="line"><span class="comment">//命名空间是Spring用来区分bean元素与其他元素。举个例子，比如A1扩展Spring定义了一个元素名为B的元素，A2同样的定义了一个元素名为B的元素，如果没有命名空间加以区分，那Spring是无法将这两个元素区分开来的。</span></div><div class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.delegate.isDefaultNamespace(root)) &#123;</div><div class="line">			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);</div><div class="line">			<span class="keyword">if</span> (StringUtils.hasText(profileSpec)) &#123;</div><div class="line">				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(</div><div class="line">						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);</div><div class="line">				<span class="keyword">if</span> (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) &#123;</div><div class="line">					<span class="keyword">return</span>;</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">        <span class="comment">//空函数体，可由开发中重写，在真正解析Document前执行</span></div><div class="line">		preProcessXml(root);</div><div class="line">		parseBeanDefinitions(root, <span class="keyword">this</span>.delegate);</div><div class="line">		<span class="comment">//同preProcessXml(root)</span></div><div class="line">		postProcessXml(root);</div><div class="line"></div><div class="line">		<span class="keyword">this</span>.delegate = parent;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">parseBeanDefinitions</span><span class="params">(Element root, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</div><div class="line">		<span class="keyword">if</span> (delegate.isDefaultNamespace(root)) &#123;</div><div class="line">			NodeList nl = root.getChildNodes();</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; nl.getLength(); i++) &#123;</div><div class="line">				Node node = nl.item(i);</div><div class="line">				<span class="keyword">if</span> (node <span class="keyword">instanceof</span> Element) &#123;</div><div class="line">					Element ele = (Element) node;</div><div class="line">					<span class="comment">//只有在默认命名空间下的元素的会被SpringIoC容器解析</span></div><div class="line">					<span class="keyword">if</span> (delegate.isDefaultNamespace(ele)) &#123;</div><div class="line">						parseDefaultElement(ele, delegate);</div><div class="line">					&#125;</div><div class="line">					<span class="keyword">else</span> &#123;</div><div class="line">						delegate.parseCustomElement(ele);</div><div class="line">					&#125;</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">else</span> &#123;</div><div class="line">			delegate.parseCustomElement(root);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processBeanDefinition</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</div><div class="line">	<span class="comment">//BeanDefinition的封装，若成功返回Holder，则说明解析成功</span></div><div class="line">		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);</div><div class="line">		<span class="keyword">if</span> (bdHolder != <span class="keyword">null</span>) &#123;</div><div class="line">			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</div><div class="line">			<span class="keyword">try</span> &#123;</div><div class="line">				<span class="comment">// 将BeanDefinition注册到容器中</span></div><div class="line">				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</div><div class="line">				getReaderContext().error(<span class="string">"Failed to register bean definition with name '"</span> +</div><div class="line">						bdHolder.getBeanName() + <span class="string">"'"</span>, ele, ex);</div><div class="line">			&#125;</div><div class="line">			<span class="comment">// Send registration event.</span></div><div class="line">			getReaderContext().fireComponentRegistered(<span class="keyword">new</span> BeanComponentDefinition(bdHolder));</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p><strong>BeanDefinitionHolder</strong>是BeanDefinition的一个封装，除了包括BeanDefinition之外，还有beanName，aliases（别名）等信息。具体的解析过程在<strong>BeanDefinitionParserDelegate</strong>中的parseBeanDefinitionElement处执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> BeanDefinitionHolder <span class="title">parseBeanDefinitionElement</span><span class="params">(Element ele, BeanDefinition containingBean)</span> </span>&#123;</div><div class="line">    <span class="comment">//获取bean定义中的id，name，aliase等属性</span></div><div class="line">		String id = ele.getAttribute(ID_ATTRIBUTE);</div><div class="line">		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);</div><div class="line"></div><div class="line">		List&lt;String&gt; aliases = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">		<span class="keyword">if</span> (StringUtils.hasLength(nameAttr)) &#123;</div><div class="line">			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);</div><div class="line">			aliases.addAll(Arrays.asList(nameArr));</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		String beanName = id;</div><div class="line">		<span class="keyword">if</span> (!StringUtils.hasText(beanName) &amp;&amp; !aliases.isEmpty()) &#123;</div><div class="line">			beanName = aliases.remove(<span class="number">0</span>);</div><div class="line">			<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</div><div class="line">				logger.debug(<span class="string">"No XML 'id' specified - using '"</span> + beanName +</div><div class="line">						<span class="string">"' as bean name and "</span> + aliases + <span class="string">" as aliases"</span>);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		<span class="keyword">if</span> (containingBean == <span class="keyword">null</span>) &#123;</div><div class="line">		<span class="comment">//检查bean的name唯一性，通过一个存有name的Set以及一个存有aliase的Set来进行判断</span></div><div class="line">			checkNameUniqueness(beanName, aliases, ele);</div><div class="line">		&#125;</div><div class="line">        <span class="comment">//对bean的详细解析入口</span></div><div class="line">		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);</div><div class="line">	...</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> AbstractBeanDefinition <span class="title">parseBeanDefinitionElement</span><span class="params">( Element ele, String beanName, BeanDefinition containingBean)</span> </span>&#123;</div><div class="line"></div><div class="line">		<span class="keyword">this</span>.parseState.push(<span class="keyword">new</span> BeanEntry(beanName));</div><div class="line"></div><div class="line">        <span class="comment">//读取了bean的className，载入到BeanDefinition中，但是没有实例化！</span></div><div class="line">		String className = <span class="keyword">null</span>;</div><div class="line">		<span class="keyword">if</span> (ele.hasAttribute(CLASS_ATTRIBUTE)) &#123;</div><div class="line">			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			String parent = <span class="keyword">null</span>;</div><div class="line">			<span class="keyword">if</span> (ele.hasAttribute(PARENT_ATTRIBUTE)) &#123;</div><div class="line">				parent = ele.getAttribute(PARENT_ATTRIBUTE);</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//生成所需的BeanDefinition</span></div><div class="line">			AbstractBeanDefinition bd = createBeanDefinition(className, parent);</div><div class="line">            <span class="comment">//根据XML中定义的内容，对BeanDefinition进行设置。</span></div><div class="line">            <span class="comment">//包括singleton，lazy-init，autowire，autowire-candidate等等，基本包含了Spring XML的所有属性</span></div><div class="line">			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);</div><div class="line">			<span class="comment">//解析其对应的描述信息（description）</span></div><div class="line">			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));</div><div class="line">            <span class="comment">//添加元数据信息</span></div><div class="line">			parseMetaElements(ele, bd);</div><div class="line">			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());</div><div class="line">			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());</div><div class="line">            <span class="comment">//解析构造函数所需参数</span></div><div class="line">			parseConstructorArgElements(ele, bd);</div><div class="line">			<span class="comment">//解析bean的一些成员属性，例如map，list，set等</span></div><div class="line">			parsePropertyElements(ele, bd);</div><div class="line">			<span class="comment">//解析bean的访问限定符</span></div><div class="line">			parseQualifierElements(ele, bd);</div><div class="line"></div><div class="line">			bd.setResource(<span class="keyword">this</span>.readerContext.getResource());</div><div class="line">			bd.setSource(extractSource(ele));</div><div class="line"></div><div class="line">			<span class="keyword">return</span> bd;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">catch</span> ...</div><div class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>比如，来看一个解析List的成员的过程<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> List&lt;Object&gt; <span class="title">parseListElement</span><span class="params">(Element collectionEle, BeanDefinition bd)</span> </span>&#123;</div><div class="line"><span class="comment">//获取value的类型</span></div><div class="line">		String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);</div><div class="line">		<span class="comment">//获取List的元素个数</span></div><div class="line">		NodeList nl = collectionEle.getChildNodes();</div><div class="line">		ManagedList&lt;Object&gt; target = <span class="keyword">new</span> ManagedList&lt;Object&gt;(nl.getLength());</div><div class="line">		target.setSource(extractSource(collectionEle));</div><div class="line">		target.setElementTypeName(defaultElementType);</div><div class="line">		target.setMergeEnabled(parseMergeAttribute(collectionEle));</div><div class="line">		parseCollectionElements(nl, target, bd, defaultElementType);</div><div class="line">		<span class="keyword">return</span> target;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">parseCollectionElements</span><span class="params">(</span></span></div><div class="line">			NodeList elementNodes, Collection&lt;Object&gt; target, BeanDefinition bd, String defaultElementType) &#123;</div><div class="line"><span class="comment">//遍历所有元素结点，判断类型是否为Element</span></div><div class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; elementNodes.getLength(); i++) &#123;</div><div class="line">			Node node = elementNodes.item(i);</div><div class="line">			<span class="keyword">if</span> (node <span class="keyword">instanceof</span> Element &amp;&amp; !nodeNameEquals(node, DESCRIPTION_ELEMENT)) &#123;</div><div class="line">				target.add(parsePropertySubElement((Element) node, bd, defaultElementType));</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>纵观整个BeanDefinition的载入过程，从XML到Resource，从Resource到Document，从Document到最后的BeanDefinition，最复杂也最重要的，当属最后一步。<br>从XML到Resource，其实只是从IO流读取一个文件。<br>从Resource到Document，是按照通用的XML解析方式解析从Resource获得的数据。<br>从Document到最后的BeanDefinition，需要根据Spring对于bean的规范，将Document中每个对应的bean结点解析出来。这其实是一个比较漫长的过程，我们知道在用XML形式定义的bean中，Spring特有的标签名有好几十个（ref，idref，scope，props…），需要一个一个去判断这些结点名存在与否，在进行相应的解析。我感觉解析过程中比较麻烦的是关于<strong>property</strong>的解析，这里说麻烦倒也不是说过程麻烦，而是除却基本的数据类型，像List，Map，Set这样的类型，解析他们的函数基本一样，只有一行代码不一样，但又不能使用泛型方法，所以看上去重复的代码量有点多。<br>BeanDefinition是一个接口，对应于Spring XML配置的标签项，它定义了一系列的函数来设置，获取这些标签值，可以认为它是bean的一个抽象表现，一般用RootBeanDefinition或者ChildBeanDefinition来实现就可以了。<br>而BeanDefinitionHolder是BeanDefinition的一个封装，同时持有bean的name，aliases（别名）以及BeanDefinition的实例，是在一个bean标签被成功解析后返回的一个Holder。<br>加载过程告一段落了，继续讲注册的过程。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//仍旧是DefaultBeanDefinitionDocumentReader类</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processBeanDefinition</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</div><div class="line"><span class="comment">//从Document中加载到BeanDefinition</span></div><div class="line">		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);</div><div class="line">		<span class="keyword">if</span> (bdHolder != <span class="keyword">null</span>) &#123;</div><div class="line">			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</div><div class="line">			<span class="keyword">try</span> &#123;</div><div class="line">			<span class="comment">//注册BeanDefinition</span></div><div class="line">			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</div><div class="line">				getReaderContext().error(<span class="string">"Failed to register bean definition with name '"</span> +</div><div class="line">						bdHolder.getBeanName() + <span class="string">"'"</span>, ele, ex);</div><div class="line">			&#125;</div><div class="line">			<span class="comment">// Send registration event.</span></div><div class="line">			getReaderContext().fireComponentRegistered(<span class="keyword">new</span> BeanComponentDefinition(bdHolder));</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">registerBeanDefinition</span><span class="params">(</span></span></div><div class="line">			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)</div><div class="line">			<span class="keyword">throws</span> BeanDefinitionStoreException &#123;</div><div class="line"></div><div class="line">		<span class="comment">// 获取bean的name，因为最终注册后是以map的形式来维护bean的</span></div><div class="line">		String beanName = definitionHolder.getBeanName();</div><div class="line">		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());</div><div class="line"></div><div class="line">		<span class="comment">// 如果有别名的话，同样为这些别名与bean构建映射关系</span></div><div class="line">		String[] aliases = definitionHolder.getAliases();</div><div class="line">		<span class="keyword">if</span> (aliases != <span class="keyword">null</span>) &#123;</div><div class="line">			<span class="keyword">for</span> (String alias : aliases) &#123;</div><div class="line">				registry.registerAlias(beanName, alias);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>来看下bean是如何被注册的。先说明下BeanDefinition默认是在DefaultListableBeanFactory中被注册的。那么也就是说，在DefaultListableBeanFactory中有维护BeanDefinition的对象。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//用beanname与BeanDefinition产生映射关系，以此维护</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, BeanDefinition&gt; beanDefinitionMap = <span class="keyword">new</span> ConcurrentHashMap&lt;String, BeanDefinition&gt;(<span class="number">256</span>);</div></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinition</span><span class="params">(String beanName, BeanDefinition beanDefinition)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</div><div class="line"></div><div class="line">		Assert.hasText(beanName, <span class="string">"Bean name must not be empty"</span>);</div><div class="line">		Assert.notNull(beanDefinition, <span class="string">"BeanDefinition must not be null"</span>);</div><div class="line"></div><div class="line">		<span class="keyword">if</span> (beanDefinition <span class="keyword">instanceof</span> AbstractBeanDefinition) &#123;</div><div class="line">			<span class="keyword">try</span> &#123;</div><div class="line">			<span class="comment">//验证BeanDefinition是否合法构建，主要是检验需要override的方法是否按照规定override</span></div><div class="line">				((AbstractBeanDefinition) beanDefinition).validate();</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</div><div class="line">				<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,</div><div class="line">						<span class="string">"Validation of bean definition failed"</span>, ex);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		BeanDefinition oldBeanDefinition;</div><div class="line"><span class="comment">//先从map中取一下，看该bean是否已经被注册。</span></div><div class="line">		oldBeanDefinition = <span class="keyword">this</span>.beanDefinitionMap.get(beanName);</div><div class="line">		<span class="keyword">if</span> (oldBeanDefinition != <span class="keyword">null</span>) &#123;</div><div class="line">		<span class="comment">//如果该bean不允许被重写，则会抛出异常</span></div><div class="line">			<span class="keyword">if</span> (!isAllowBeanDefinitionOverriding()) &#123;</div><div class="line">				<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,</div><div class="line">						<span class="string">"Cannot register bean definition ["</span> + beanDefinition + <span class="string">"] for bean '"</span> + beanName +</div><div class="line">						<span class="string">"': There is already ["</span> + oldBeanDefinition + <span class="string">"] bound."</span>);</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (oldBeanDefinition.getRole() &lt; beanDefinition.getRole()) &#123;</div><div class="line">			<span class="comment">//Role有三种，ROLE_APPLICATION（0），ROLE_SUPPORT（1），ROLE_INFRASTRUCTURE（2），进入该分支意味着，BeanDefinition的Role会被改变</span></div><div class="line">				<span class="keyword">if</span> (<span class="keyword">this</span>.logger.isWarnEnabled()) &#123;</div><div class="line">					<span class="keyword">this</span>.logger.warn(<span class="string">"Overriding user-defined bean definition for bean '"</span> + beanName +</div><div class="line">							<span class="string">"' with a framework-generated bean definition: replacing ["</span> +</div><div class="line">							oldBeanDefinition + <span class="string">"] with ["</span> + beanDefinition + <span class="string">"]"</span>);</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//发出一个警告，告知BeanDefinition会被一个新的不同的BeanDefinition所覆盖。</span></div><div class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (!beanDefinition.equals(oldBeanDefinition)) &#123;</div><div class="line">				<span class="keyword">if</span> (<span class="keyword">this</span>.logger.isInfoEnabled()) &#123;</div><div class="line">					<span class="keyword">this</span>.logger.info(<span class="string">"Overriding bean definition for bean '"</span> + beanName +</div><div class="line">							<span class="string">"' with a different definition: replacing ["</span> + oldBeanDefinition +</div><div class="line">							<span class="string">"] with ["</span> + beanDefinition + <span class="string">"]"</span>);</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//允许重写该BeanDefinition</span></div><div class="line">			<span class="keyword">else</span> &#123;</div><div class="line">				<span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</div><div class="line">					<span class="keyword">this</span>.logger.debug(<span class="string">"Overriding bean definition for bean '"</span> + beanName +</div><div class="line">							<span class="string">"' with an equivalent definition: replacing ["</span> + oldBeanDefinition +</div><div class="line">							<span class="string">"] with ["</span> + beanDefinition + <span class="string">"]"</span>);</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//把BeanDefinition放到map中去，算是完成注册</span></div><div class="line">			<span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">else</span> &#123;</div><div class="line">		<span class="comment">//检查该factory的bean创建是否开始了</span></div><div class="line">			<span class="keyword">if</span> (hasBeanCreationStarted()) &#123;</div><div class="line">			<span class="comment">//注册过程需要保持数据的一致性，所以用synchronized加锁</span></div><div class="line">				<span class="keyword">synchronized</span> (<span class="keyword">this</span>.beanDefinitionMap) &#123;</div><div class="line">					<span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition);</div><div class="line">					<span class="comment">//新注册一个BeanDefinition，所以list长度+1，它所持有的是所有bean的name</span></div><div class="line">					List&lt;String&gt; updatedDefinitions = <span class="keyword">new</span> ArrayList&lt;String&gt;(<span class="keyword">this</span>.beanDefinitionNames.size() + <span class="number">1</span>);</div><div class="line">					updatedDefinitions.addAll(<span class="keyword">this</span>.beanDefinitionNames);</div><div class="line">					updatedDefinitions.add(beanName);</div><div class="line">					<span class="keyword">this</span>.beanDefinitionNames = updatedDefinitions;</div><div class="line">					<span class="comment">//如果单例模式的bean名单中有该bean的name，那么移除掉它。</span></div><div class="line">					<span class="comment">//意味着，将一个原本是单例模式的bean重新注册成一个普通的bean</span></div><div class="line">					<span class="keyword">if</span> (<span class="keyword">this</span>.manualSingletonNames.contains(beanName)) &#123;</div><div class="line">						Set&lt;String&gt; updatedSingletons = <span class="keyword">new</span> LinkedHashSet&lt;String&gt;(<span class="keyword">this</span>.manualSingletonNames);</div><div class="line">						updatedSingletons.remove(beanName);</div><div class="line">						<span class="keyword">this</span>.manualSingletonNames = updatedSingletons;</div><div class="line">					&#125;</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">else</span> &#123;</div><div class="line">				<span class="comment">// 仍处于启动阶段，bean还没有开始注册</span></div><div class="line">				<span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition);</div><div class="line">				<span class="keyword">this</span>.beanDefinitionNames.add(beanName);</div><div class="line">				<span class="keyword">this</span>.manualSingletonNames.remove(beanName);</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">this</span>.frozenBeanDefinitionNames = <span class="keyword">null</span>;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		<span class="keyword">if</span> (oldBeanDefinition != <span class="keyword">null</span> || containsSingleton(beanName)) &#123;</div><div class="line">		<span class="comment">//做的其实是清除key = beanName 的缓存。</span></div><div class="line">		<span class="comment">//因为oldBeanDefinition如果存在，且执行到了这里也没有抛出异常，说明该BeanDefinition已经被覆盖，缓存需要更新。</span></div><div class="line">		<span class="comment">//若是单例模式的bean对象Set中包含该beanName，执行到这里说明该BeanDefinition已经从一个单例模式的bean变为了一个普通的bean，所以缓存也需要更新</span></div><div class="line">			resetBeanDefinition(beanName);</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>到这里，BeanDefinition的注册就完成了一大半了，剩下的部分就是把该BeanDefinition对应的aliases（别名）也分别注册进去，同样也是用一个map来维护，其中key为beanName，value为aliase，这里就不给出代码了。<br>这里简单说明几个问题：</p>
<blockquote>
<p>1.为何<strong>hasBeanCreationStarted()</strong>为true时，需要进行同步？<br>先看下hasBeanCreationStarted()做了什么。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 存的是那些至少被创建了一次的bean的name</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> Set&lt;String&gt; alreadyCreated =</div><div class="line">			Collections.newSetFromMap(<span class="keyword">new</span> ConcurrentHashMap&lt;String, Boolean&gt;(<span class="number">256</span>));</div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">hasBeanCreationStarted</span><span class="params">()</span> </span>&#123;</div><div class="line"><span class="comment">//判断的条件是这个Set是否为空。</span></div><div class="line">		<span class="keyword">return</span> !<span class="keyword">this</span>.alreadyCreated.isEmpty();</div><div class="line">	&#125;</div><div class="line">	</div><div class="line"><span class="comment">//要知道他什么时候为空，我觉得可以先去看下它什么是后不为空，也就是什么时候进行add操作</span></div><div class="line"></div><div class="line"><span class="comment">//该函数在AbstractBeanFactory中，只有在doGetBean(...)中出现过，该操作是将BeanDefinition实例化成想要的bean</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">markBeanAsCreated</span><span class="params">(String beanName)</span> </span>&#123;</div><div class="line">		<span class="keyword">if</span> (!<span class="keyword">this</span>.alreadyCreated.contains(beanName)) &#123;</div><div class="line">			<span class="keyword">this</span>.alreadyCreated.add(beanName);</div><div class="line">			clearMergedBeanDefinition(beanName);</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
</blockquote>
<p>这样也就明确了只有某个bean被实例化后，alreadyCreated集合才有可能不为空。<br>根据Spring容器初始化的顺序，会先实例化所有的单例模式的bean，按道理讲，实例化后的alreadyCreated一般不为空。但是上面讲的是内部容器，也就是BeanFactory这一分支，不涉及ApplicationContext分支。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">       Resource resource = <span class="keyword">new</span> ClassPathResource(<span class="string">"beans.xml"</span>);</div><div class="line">       BeanFactory factory = <span class="keyword">new</span> XmlBeanFactory(resource);</div><div class="line">       <span class="keyword">boolean</span> s = factory.containsBean(<span class="string">"mybean"</span>);</div><div class="line">       &#125;</div></pre></td></tr></table></figure></p>
<p>就像上面这样使用的话，整个流程就是：</p>
<pre><code>加载xml----&gt;解析xml到Document----&gt;解析Document到BeanDefinition----&gt;注册BeanDefinition（知道这个流程后，自己也能写个简单的IoC容器）
并不像外部容易初始化那般复杂。所以该问题留到讲外部容器初始化过程的时候再继续讨论
</code></pre><p>###4.小结<br>XmlBeanFactory而言，它扩展于DefaultListableBeanFactory，一般的，这种情况下只需要实现该BeanFactory对应的资源读取器Reader，而注册及其他部分，在DefaultListableBeanFactory中已经完成了。<br>实际上，DefaultListableBeanFactory就是作为Spring内部默认实际使用的BeanFactory而存在的。<br>对于内部容器初始化，过程并不复杂。就如同上面提到的一样，流程很简单，但是部分操作（bean的注册，BeanDefinition的生成）与外部容器的初始化都是通用的，所以值得关注。尤其是BeanDefinition生成的时候，Spring解析的及其详细，包括作用范围，重写的函数，各种类型成员的解析等等，一个bean所能表示的所有的信息都被解析到BeanDefinition中。</p>
<hr>
<p>理解有误之处，请大家多多指正。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring/" rel="tag">#spring</a>
          
            <a href="/tags/ioc/" rel="tag">#ioc</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/28/ZeroMQ/" rel="next" title="从源码分析ZeroMQ">
                <i class="fa fa-chevron-left"></i> 从源码分析ZeroMQ
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/28/spring-ioc-2/" rel="prev" title="从源码解析SpringIoc机制（2）">
                从源码解析SpringIoc机制（2） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/08/28/spring-ioc-1/"
           data-title="源码角度解析SpringIoC的机制" data-url="http://yoursite.com/2016/08/28/spring-ioc-1/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/touxiang.jpg"
               alt="钱伟峰" />
          <p class="site-author-name" itemprop="name">钱伟峰</p>
          <p class="site-description motion-element" itemprop="description">每天进步一点点</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">21</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-简介"><span class="nav-number">1.</span> <span class="nav-text">1. 简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-层级示意图"><span class="nav-number">2.</span> <span class="nav-text">2. 层级示意图</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钱伟峰</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"qianweifeng"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
